import axios from "axios";
import { BASEURL } from "../env";
import intercept from "./intercept";
import createSecret from "./createSecret.js";
import store from "../../store/index";

const instance = axios.create({
  baseURL: BASEURL,
  timeout: 6000,
  headers: {
    "Content-Type": "application/json",
  },
});

// 请求拦截
instance.interceptors.request.use(
  (config) => {
    config.headers = {
      token: store.state.userToken,
      secret: createSecret(),
    };
    return config;
  },
  (error) => {
    intercept(error);
    return Promise.error(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  // 请求成功
  (res) => {
    return res.data;
  },
  // 请求失败
  (error) => {
    if (error.response) {
      let data = error.response.data;
      intercept(data);
      return Promise.reject(error.response.data);
    } else {
      return Promise.reject(error);
    }
  }
);

export default instance;
